package com.yanx.system.web.infra.listener;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.yanx.common.command.executor.CommandExecutor;
import com.yanx.common.core.event.LoginInforRecordEvent;
import com.yanx.common.enums.DataStatus;
import com.yanx.common.utils.Address_;
import com.yanx.common.utils.Servlet_;
import com.yanx.system.base.command.MonLoginInforCreateCmd;
import com.yanx.system.base.model.dto.MonLoginInforDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author gotanks
 * @create 2023/6/5
 */
@Slf4j
@Component
public class LoginInforRecordListener implements ApplicationListener<LoginInforRecordEvent> {

    @Autowired
    private CommandExecutor commandExecutor;

    @Async
    @Override
    public void onApplicationEvent(LoginInforRecordEvent event) {
        String username = event.getUsername();
        int status = event.getStatus();
        String message = event.getMessage();

        UserAgent userAgent = UserAgentUtil.parse(Servlet_.getRequest().getHeader("User-Agent"));
        String ip = Servlet_.getClientIP(Servlet_.getRequest());
        // 获取客户端操作系统
        String os = userAgent.getOs().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        //获取地址
        String address = Address_.getRealAddressByIP(ip);
        // 封装对象
        MonLoginInforDto logininfor = new MonLoginInforDto();
        logininfor.setUserName(username);
        logininfor.setIpaddr(ip);
        logininfor.setLoginLocation(address);
        logininfor.setBrowser(browser);
        logininfor.setOs(os);
        logininfor.setMsg(message);
        logininfor.setStatus(DataStatus.values()[status]);
        // 插入数据
        commandExecutor.execute(new MonLoginInforCreateCmd(logininfor));
    }
}
